package com.app.Timer;

import com.app.model.cache.RedisKeys;
import com.app.model.main.Article;
import com.app.model.main.CommentsOfArticle;
import com.app.model.util.CommonFlag;
import com.app.repository.interfaces.ApprovalMapper;
import com.app.repository.interfaces.ArticleMapper;
import com.app.repository.interfaces.CommentsOfArticleMapper;
import com.app.repository.interfaces.UserMapper;
import com.app.support.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Created by Lichaojie on 2017/3/26. It's a beautiful day.
 */
@Component
public class CacheTimer {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ApprovalMapper approvalMapper;
    @Autowired
    private CommentsOfArticleMapper commentsOfArticleMapper;

    /**
     * 清空用户的刷新纪录
     */
    @Scheduled(cron = "00 00 00 * * ?")
    public void emptyUpdateHistory(){
        long maxId = userMapper.getMaxId();
        for(long i = 1; i <= maxId; i ++){
            redisUtil.remove(RedisKeys.RECOMMEND_SHARE_ARTICLE_UPDATE_HISTORY + i);
        }
    }

    /**
     * 使缓存中的点赞数和评论数与数据库一致，每天凌晨自动同步一次
     */
    @Scheduled(cron = "00 00 00 * * ?")
    public void makeConsistent(){
        long maxId = articleMapper.getMaxId();
        for(long i = 1 ; i <= maxId; i ++){
            Article article = articleMapper.selectByPrimaryKey(i);
            if(article.getFlag() == 1){
                long approvalNum = approvalMapper.getApprovalNumber(i, CommonFlag.ARTICLE);
                long commentsNum = commentsOfArticleMapper.getCommentsNumber(i);

                String approvalKey = RedisKeys.APPROVAL_NUMBER.ARTICLE + i;
                if(redisUtil.exists(approvalKey)){
                    redisUtil.remove(approvalKey);
                }
                redisUtil.set(approvalKey,approvalNum);

                String commentsKey = RedisKeys.COMMENTS_NUMBER_OF_ARTICLE + i;
                if(redisUtil.exists(commentsKey)){
                    redisUtil.remove(commentsKey);
                }
                redisUtil.set(commentsKey,commentsNum);
            }
        }
    }

}
